<template>
  <div class="register">
    <!-- 顶部                   注册 -->
    <van-nav-bar title="注册">
      <!-- 左侧 -->
      <template #left>
        <van-icon name="arrow-left" color="#fff" @click="go" />
      </template>
      <!-- 右侧 -->
      <template #right>
        <router-link to="/login">登录</router-link>
      </template>
    </van-nav-bar>

    <!-- 通知栏 -->
    <van-notice-bar
      left-icon="volume-o"
      text="在代码阅读过程中人们说脏话的频率是衡量代码质量的唯一标准。"
    />
    <!-- 头像 -->
    <van-image
      class="reg_img"
      width="8rem"
      height="8rem"
      :src="require('../assets/icon.png')"
    />

    <!-- 表单 -->
    <van-form @submit="onSubmit">
      <!-- 用户名 -->
      <van-field
        v-model="username"
        clearable
        name="用户名"
        label="用户名"
        placeholder="请输入用户名"
        :rules="[{ required: true }]"
      >
      </van-field>
      <van-field
        v-model="nickname"
        clearable
        name="昵称"
        label="昵称"
        placeholder="请输入昵称"
        :rules="[{ required: true }]"
      >
      </van-field>
      <!-- 手机号 -->
      <van-field
        v-model="phone"
        center
        clearable
        label="手机号码"
        placeholder="请输入手机号码"
        :rules="[
          { required: true },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式错误！' },
        ]"
      />
      <!-- 短信 -->
      <van-field
        v-model="sms"
        center
        clearable
        label="短信验证码"
        placeholder="请输入短信验证码"
        :rules="[{ required: true }]"
      >
        <!-- 验证码按钮 -->
        <template #button>
          <!-- 启用 -->
          <van-button
            v-if="btnStatus == 1"
            size="small"
            native-type="button"
            type="primary"
            @click="onSms"
            >发送验证码</van-button
          >
          <!-- 禁用 -->
          <van-button
            v-else
            size="small"
            native-type="button"
            :disabled="true"
            type="primary"
            @click="onSms"
            >{{ content }}</van-button
          >
        </template>
      </van-field>
      <!-- 密码 -->
      <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="请输入密码"
        :rules="[{ required: true }]"
      />
      <!-- 确认密码 -->
      <van-field
        v-model="passwordState"
        type="password"
        name="确认密码"
        label="确认密码"
        placeholder="请再次确认密码"
        :rules="[{ required: true }]"
      />
      <!-- 选择地区 -->
      <van-field
        readonly
        clickable
        name="area"
        :value="value"
        label="地区选择"
        placeholder="点击选择省市区"
        @click="showArea = true"
        :rules="[{ required: true }]"
      />
      <van-popup v-model="showArea" position="bottom">
        <van-area
          :area-list="areaList"
          @confirm="onConfirm"
          @cancel="showArea = false"
        />
      </van-popup>
      <!-- 注册按钮 -->
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >注册</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { Toast } from "vant";
import { areaList } from "@vant/area-data";
export default {
  data() {
    return {
      // 表单基本信息
      username: "",
      nickname: "",
      phone: "",
      password: "",
      passwordState: "",

      // 选择地区
      value: "",
      showArea: false,
      areaList, // 地区数据

      // 发送验证码
      sms: "", //用户输入的验证码
      randomNum: "", // 随机生成六位数验证码
      btnStatus: "1", //默认启用按钮
      content: "60s后重新发送", //页面显示
      totalTime: 60, //默认值60s
    };
  },
  methods: {
    // 定义方法，验证确认密码
    checkRepwd() {
      // 判断两次输入的密码是否一致
      if (this.password == this.passwordState) {
        // 满足则验证成功
        return true;
      } else {
        // 验证失败
        return false;
      }
    },
    // 定义方法，验证密码
    checkPwd() {
      let reg = /^\d{6}$/;
      //  验证正则表达式
      if (reg.test(this.password)) {
        // 验证成功
        return true;
      } else {
        // 验证失败
        return false;
      }
    },
    // 定义方法，验证用户名
    checkUsername() {
      // 验证用户名  要求单词字符6~15位 [A-Za-z0-9_]
      let reg = /^\w{6,15}$/;
      if (reg.test(this.username)) {
        // 验证成功
        return true;
      } else {
        // 验证失败
        return false;
      }
    },
    // 定义方法，验证码判断
    checkSms() {
      if (this.randomNum == this.sms) {
        return true;
      } else {
        return false;
      }
    },
    // 点击注册之后执行，验证表单
    onSubmit() {
      // 验证码验证
      if (this.checkSms()) {
        // 判断密码输入是否一致
        if (this.checkRepwd()) {
          // 验证密码正则表达式
          if (this.checkPwd()) {
            // 三个函数方法同时满足了,就提交表单申请
            if (this.checkUsername()) {
              this.axios
                .post(
                  "/register1",
                  `username=${this.username}&password=${this.password}&nickname=${this.nickname}&phone=${this.phone}`
                )
                .then((result) => {
                  // console.log(result);
                  // 接收数据库返回的验证结果
                  if (result.data.code == 200) {
                    Toast.success("注册成功");
                    this.$router.push("/login");
                  } else if (result.data.code == 201) {
                    Toast.fail("注册失败");
                  }
                });
            } else {
              Toast.fail("用户名格式不对");
            }
          } else {
            Toast.fail("密码格式不对");
          }
        } else {
          Toast.fail("两次输入的密码不一致");
        }
      } else {
        Toast.fail("验证码不正确");
      }
    },
    // 选择地区
    onConfirm(values) {
      this.value = values
        .filter((item) => !!item)
        .map((item) => item.name)
        .join("/");
      this.showArea = false;
    },
    // 回退一步
    go() {
      this.$router.go(-1);
    },
    // 短信验证码
    onSms() {
      this.btnStatus = "0";
      // 电话号码的正则表达式
      let reg = /^1[3-9]\d{9}$/;
      if ((this.phone != "") & reg.test(this.phone)) {
        let num = Math.random()
          .toFixed(6)
          .slice(-6);
        console.log(`给用户电话:${this.phone}发送短信,验证码是:${num}`);
        this.randomNum = num;
      } else {
        Toast.fail("输入正确的电话号码才能发送验证码");
      }
      // 限制发短信请求,60s一次
      this.content = this.totalTime + "s后重新发送";
      let clock = window.setInterval(() => {
        this.totalTime--;
        this.content = this.totalTime + "s后重新发送";
        if (this.totalTime < 0) {
          window.clearInterval(clock);
          this.totalTime = 60;
          this.btnStatus = "1"; //这里重新开启
        }
      }, 1000);
    },
  },
};
</script>

<style scoped>
.register {
  text-align: center;
}
.register .van-nav-bar {
  /* 统一主色调 */
  background-color: rgb(123, 183, 253);
}
.register .van-nav-bar__title,
.register .van-nav-bar__left a,
.register .van-nav-bar__right a {
  color: white;
}
.register .van-button {
  border: 0;
}
.register .reg_img {
  margin-top: 30px;
  margin-bottom: 20px;
}
</style>
